from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from .models import Pile
from .connectors import pile_connections, connect_pile, disconnect_pile
import threading
import logging

logger = logging.getLogger('django')

@receiver(post_save, sender=Pile)
def pile_saved(sender, instance, created, **kwargs):
    """当充电桩保存时自动连接或更新连接状态"""

    # 使用线程延迟连接操作，避免阻塞主线程
    def delayed_connect():
        if instance.logged_in:
            # 只有在需要连接且尚未连接时才连接
            if instance.pk not in pile_connections:
                connect_pile(instance.pk)
        else:
            # 如果桩状态变为未登录，断开连接
            if instance.pk in pile_connections:
                disconnect_pile(instance.pk)

    # 使用新线程执行连接操作
    if not hasattr(instance, '_connection_thread_running'):
        thread = threading.Thread(target=delayed_connect, daemon=True)
        instance._connection_thread_running = True
        thread.start()


@receiver(pre_delete, sender=Pile)
def pile_deleted(sender, instance, **kwargs):
    """当充电桩删除前断开连接"""
    if instance.pk in pile_connections:
        disconnect_pile(instance.pk)